package edu.buaa.resourceManager;

import edu.buaa.resourceManager.helper.Utils;
import org.slf4j.Logger;

import java.io.*;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * Created by sjh on 17-5-21.
 */
public class Config
{
    public static final String LAST_FILE_CHOOSE_DIR = "user.lastFileChooseDir";
    public static final String DEFAULT_CONFIG_FILE = "default.config.file";
    private static Properties prop = new Properties();
    private static boolean updateProp = false;
    private static Logger log = Utils.getDevLogger();

    static {
        try {
            FileInputStream input = new FileInputStream("config.properties");
            prop.load(input);
        } catch (FileNotFoundException ignore) {
            try {
                prop.load(Config.class.getResourceAsStream("/config.properties"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        log.debug("{}", prop.getProperty(LAST_FILE_CHOOSE_DIR, "not found"));
    }
    public static AtomicBoolean autoRefresh = new AtomicBoolean(true);

    public static void toFile() throws IOException {
        if(Config.isUpdate()) {
            String configFile = prop.getProperty(Config.DEFAULT_CONFIG_FILE, "config.properties");
            File f = new File(configFile);
            if (f.exists()) {
                Utils.getDevLogger().debug("overwrite config file: {}", f.getAbsolutePath());
            }
            OutputStream output = new FileOutputStream(configFile);
            // save properties to project root folder
            prop.store(output, "~~~~ Configuration file of Resource Manager ~~~~");
        }
    }

    public static void set(String key, String value){
        updateProp = true;
        prop.setProperty(key, value);
    }

    public static boolean isUpdate(){
        return updateProp;
    }

    public static String get(String key){
        return prop.getProperty(key, "");
    }
}
